import React, { PureComponent } from 'react';
import { Tabs, Tree } from 'antd';

const { TabPane } = Tabs;
const { TreeNode } = Tree;

export default class PermissionSelect extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      autoExpandParent: true,
      activeKey: '1',
      checked: {},
    };
  }

  onCheck = (checkedKeys, { halfCheckedKeys }) => {
    const { onChange } = this.props;
    const { activeKey, checked } = this.state;
    const tmp = { ...checked };
    tmp[activeKey] = [...checkedKeys, ...halfCheckedKeys];
    this.setState({
      checked: tmp,
    });
    const arr = [];
    Object.keys(tmp).forEach(i => {
      arr.push(...tmp[i])
    })
    console.log('============', arr)
    onChange(arr);
  };

  onTabChange = activeKey => {
    this.setState({
      activeKey,
    });
  };

  renderTreeNodes = data => {
    const { actions, vKey } = this.props;
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item[vKey]} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={actions[item.action]} key={item[vKey]} dataRef={item} />;
    });
  };

  render() {
    const { tabs, value } = this.props;
    const { activeKey, checked } = this.state;
    console.log('=======2222====', checked, value);

    return (
      <Tabs defaultActiveKey={activeKey} onChange={this.onTabChange}>
        {tabs.map((item, index) => (
          <TabPane tab={item.title} key={`${index + 1}`}>
            {`${index + 1}` === activeKey && (
              <Tree
                checkable
                defaultExpandAll
                checkedKeys={checked[activeKey]}
                onCheck={this.onCheck}
                autoExpandParent={this.state.autoExpandParent}
              >
                {this.renderTreeNodes(item.data)}
              </Tree>
            )}
          </TabPane>
        ))}
      </Tabs>
    );
  }
}
